package com.xci.sys.controller;


import com.xci.core.annotation.Authorize;
import com.xci.core.base.RestMessage;
import com.xci.core.base.WebController;
import com.xci.core.exceptions.EntityNotFoundException;
import com.xci.core.helper.ConvertHelper;
import com.xci.core.helper.ExcelHelper;
import com.xci.core.helper.Helper;
import com.xci.core.helper.TreeHelper;
import com.xci.core.internal.Const;
import com.xci.core.web.Tree;
import com.xci.core.web.TreeNode;
import com.xci.core.web.TreeNodeIndex;
import com.xci.sys.entity.SysDic;
import com.xci.sys.entity.SysDicCategory;
import com.xci.sys.filter.DicFilter;
import com.xci.sys.service.DicCategoryService;
import com.xci.sys.service.DicService;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.internal.util.StringHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 系统字典明细控制器
 */
@Authorize
@Slf4j
@Controller
@RequestMapping("/sys/dic")
public class DicController extends WebController {
    @Resource
    private DicCategoryService dicCategoryService;//字典类型服务
    @Resource
    private DicService dicService;//字典服务

    //region 页面视图

    /**
     * 字典明细首页
     */
    @GetMapping("/{dicCode}")
    public String index(@PathVariable String dicCode, ModelMap map) {
        if (Helper.isBlank(dicCode)) throw new IllegalArgumentException("请指定字典编码");
        var dicCategory = dicCategoryService.selectByCode(dicCode);
        if (dicCategory == null) throw new IllegalArgumentException(Helper.format("指定的字典编码[{}]无效", dicCode));

        map.put("dicCode", dicCategory.getCode());
        map.put("dicName", dicCategory.getName());
        return "sys/dic/index";
    }

    /**
     * 字典明细新建页面
     */
    @GetMapping("/create")
    @Authorize(code = "")
    public String create(String parentId, String dicCode, ModelMap map) {
        createMark(map);
        SysDic entity = new SysDic();
        entity.setId(Helper.nextIdStr());
        entity.setParentId(parentId);
        entity.setCode(dicCode);
        entity.setStatus(true);
        map.put("entity", entity);
        map.put("parentName", getParentName(parentId));
        return "sys/dic/edit";
    }

    /**
     * 字典明细编辑页面
     */
    @GetMapping("/edit")
    @Authorize(code = "")
    public String edit(String id, ModelMap map) {
        SysDic entity = dicService.selectById(id);
        if (entity == null) throw new EntityNotFoundException(id);
        map.put("entity", entity);
        map.put("parentName", getParentName(entity.getParentId()));
        return "sys/dic/edit";
    }

    private String getParentName(String id) {
        String parentName = Const.EMPTY;
        if (Helper.isNotBlank(id) && !id.equals(Const.ROOT_NODE_ID)) {
            var parentModel = dicService.selectById(id);
            if (parentModel != null) {
                parentName = parentModel.getName();
            }
        }
        if (Helper.isBlank(parentName)) {
            parentName = "顶层";
        }
        return parentName;
    }

    // private String getDicName(String dicId) {
    //     String dicName = Const.EMPTY;
    //     if (Helper.isNotBlank(dicId) && !dicId.equals(Const.ROOT_NODE_ID)) {
    //         var parentModel = dicService.selectById(dicId);
    //         if (parentModel!= null){
    //             dicName = parentModel.getName();
    //         }
    //     }
    //     return dicName;
    // }

    /**
     * 字典明细详细页面
     */
    @GetMapping("/details")
    public String details(String id, ModelMap map) {
        SysDic entity = dicService.selectById(id);
        if (entity == null) throw new EntityNotFoundException(id);
        map.put("entity", entity);
        return "sys/dic/details";
    }

    //endregion

    //region 数据处理

    // /**
    //  * 字典明细Tree
    //  */
    // @ResponseBody
    // @GetMapping("/tree")
    // public Object tree(@RequestParam Map<String, String> params) {
    //     String dicCode = params.get("dicCode");
    //     List<Tree> list = dicDetailsService.queryTreeModelList(dicCode, 1);
    //     return RestMessage.tree(list);
    // }

    /**
     * 字典明细表格数据
     */
    @ResponseBody
    @GetMapping("/grid")
    @Authorize(code = "")
    public Object grid(DicFilter filter) {
        List<SysDic> list = dicService.selectList(filter);
        return RestMessage.grid(list);
    }

    /**
     * 保存新增字典明细
     */
    @ResponseBody
    @PostMapping("/createSave")
    @Authorize(code = "")
    public RestMessage createSave(@ModelAttribute SysDic entity) {
        return dicService.update(entity);
    }

    /**
     * 保存修改字典明细
     */
    @ResponseBody
    @PostMapping("/updateSave")
    @Authorize(code = "")
    public RestMessage updateSave(@ModelAttribute SysDic entity) {
        return dicService.update(entity);
    }

    /**
     * 保存拖拽数据(父节点和路径)
     */
    @ResponseBody
    @PostMapping("/dnd")
    @Authorize(code = "")
    public RestMessage dnd(@RequestBody List<TreeNodeIndex> nodeIndexs) {
        return dicService.batchUpdate(TreeHelper.toPrimaryKeyValues(nodeIndexs));
    }

    /**
     * 修改字典明细启用状态
     */
    @ResponseBody
    @PostMapping("/status")
    @Authorize(code = "")
    public RestMessage status(String id, Integer status) {
        return dicService.updateStatus(id, ConvertHelper.toBool(status));
    }

    /**
     * 删除字典明细
     */
    @ResponseBody
    @PostMapping("/delete")
    @Authorize(code = "")
    public RestMessage delete(String id) {
        return dicService.delete(id);
    }

    /**
     * 导出字典明细
     */
    @GetMapping("/export")
    @Authorize(code = "")
    public void export(DicFilter filter) {
        String title = "系统数据字典";
        if (Helper.isBlank(filter.getCode())) throw new IllegalArgumentException("请指定字典编码");
        SysDicCategory dicCategory = dicCategoryService.selectByCode(filter.getCode());
        if (dicCategory != null) {
            title = Helper.format("{}-{}", title, dicCategory.getName());
        }
        ExcelHelper.exportWeb(dicService.selectList(filter), SysDic.class, title);
    }

    // /**
    //  * 查询字典明细列表
    //  */
    // @ResponseBody
    // @GetMapping("/queryListByDicCode/{dicCode}")
    // public RestMessage queryListByDicCode(@PathVariable String dicCode) {
    //     if (Helper.isBlank(dicCode)){
    //         return RestMessage.fail("请指定数据字典编码");
    //     }
    //     return new RestMessage<>(dicService.querySimpleByDicCode(dicCode));
    // }

    /**
     * 查询字典明细树列表
     */
    @ResponseBody
    @GetMapping("/queryTreeByDicCode/{dicCode}")
    public Object queryTreeByDicCode(@PathVariable String dicCode) {
        if (Helper.isBlank(dicCode)) {
            return RestMessage.fail("请指定数据字典编码");
        }
        List<SysDic> list = dicService.selectListByCode(dicCode);
        List<TreeNode> models = dicService.convertToNodeList(list);
        return RestMessage.tree(models);
    }

    //endregion
}
